#include "StdAfx.h"
#include "ChunkModel.h"

#include "ChunkFileSerializer.h"
#include "ChunkManager.h"


#include "3rd_part/xml/TiXmlUtility.h"

using namespace ChunkSystem;

ChunkModel::ChunkModel( ChunkItem* pOwner )
	:ChunkItem( "ChunkModel", pOwner )
{
	
}

ChunkModel::~ChunkModel(void)
{
}

bool ChunkModel::Load( TiXmlElement* pChunkItemData )
{
	TiXmlHandle ptrChunkItemDataSection(pChunkItemData);
	//relative resource path
	TiXmlHandle ptrResPath = ptrChunkItemDataSection.FirstChild("resource");
	assert( ptrResPath.FirstChild().ToText() != NULL );
	m_strResPath = ptrResPath.FirstChild().ToText()->Value();
	//transformation
	TiXmlHandle ptrTransformSection = ptrChunkItemDataSection.FirstChild("Transformation");
	assert( ptrTransformSection.ToElement() != NULL );
	m_matWorldTM = TiXmlUtility::ReadMatrix( ptrTransformSection );

	//create visible for testing.
	if( m_pVisible != NULL )
	{
		IRenderer* pRenderer = ChunkManager::GetInstance().GetRenderer();
		assert( pRenderer != NULL );
		m_pVisible->Load( pRenderer );
	}

	return true;
}

std::string ChunkModel::GetResPath( void ) const
{
	return m_strResPath;
}

void ChunkModel::Unload( void )
{

}

void ChunkModel::UpdateAABB( void )
{
}
	
void ChunkModel::CreateVisible(IRenderableFactory* pFac)
{
	if( m_pVisible != NULL )
	{
		assert( false );
		return;
	}

	m_pVisible = pFac->Create(this);
}

void ChunkModel::DestoryVisible(void)
{
	if( m_pVisible == NULL )
	{
		assert( false );
		return;
	}

	delete m_pVisible;
	m_pVisible = NULL;
}

void ChunkModel::DrawVisible( IRenderer* pRenderer )
{
	if( m_pVisible != NULL )
		m_pVisible->Draw( pRenderer );
}
////////////////////////////////////////////////////////////////////////////////////////////////////

ChunkModelFactory::ChunkModelFactory()
{
}

ChunkModelFactory::~ChunkModelFactory()
{
}

String ChunkModelFactory::GetType(void)
{
	return ChunkFileSerializer::GetTag( ChunkFileSerializer::eModel );
}

ChunkItem* ChunkModelFactory::Create( ChunkItem* pOwner, TiXmlElement* pChunkItemData )
{
	return new ChunkModel( pOwner );
}